package com.witmore.neutron.ai.web.apiv2.controller;

import com.jk.common.response.ResponsePageResult;
import com.jk.common.response.ResponseResult;
import com.witmore.neutron.ai.web.annotation.RequiresPermission;
import com.witmore.neutron.ai.web.apiv2.controller.vo.UserKeyCreateParam;
import com.witmore.neutron.ai.web.apiv2.controller.vo.UserKeyCreateResponse;
import com.witmore.neutron.ai.web.apiv2.controller.vo.UserKeyDeleteParam;
import com.witmore.neutron.ai.web.apiv2.controller.vo.UserKeyListResponse;
import com.witmore.neutron.ai.web.apiv2.controller.vo.UserKeyQueryParam;
import com.witmore.neutron.ai.web.apiv2.controller.vo.UserKeyUpdateParam;
import com.witmore.neutron.ai.web.service.UserKeyService;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * V2 用户API密钥相关接口
 * Author: 豆子高
 * Date: 2025/09/04
 */
@Slf4j
@RestController
@RequestMapping("/v2/userKey")
public class UserKeyControllerV2 {

    @Autowired
    private UserKeyService userKeyService;

    /**
     * 创建用户API密钥
     */
    @RequiresPermission("user:key:create")
    @PostMapping("/create")
    public ResponseResult<UserKeyCreateResponse> createUserKey(@Valid @RequestBody UserKeyCreateParam createParam) {
        log.info("创建用户API密钥请求: {}", createParam);
        return userKeyService.createUserKey(createParam);
    }


    /**
     * 删除用户API密钥
     */
    @RequiresPermission("user:key:delete")
    @PostMapping("/delete")
    public ResponseResult<Void> deleteUserKey(@Valid @RequestBody UserKeyDeleteParam deleteParam) {
        log.info("删除用户API密钥请求: {}", deleteParam);
        return userKeyService.deleteUserKey(deleteParam.getId());
    }

    /**
     * 编辑用户API密钥
     */
    @RequiresPermission("user:key:update")
    @PostMapping("/update")
    public ResponseResult<Void> updateUserKey(@Valid @RequestBody UserKeyUpdateParam updateParam) {
        log.info("编辑用户API密钥请求: {}", updateParam);
        return userKeyService.updateUserKey(updateParam);
    }

    /**
     * 分页查询用户API密钥列表
     */
    @RequiresPermission("user:key:list")
    @GetMapping("/list")
    public ResponsePageResult<UserKeyListResponse> getUserKeyList(UserKeyQueryParam queryParam) {
        log.info("分页查询用户API密钥列表请求: {}", queryParam);
        try {
            return ResponsePageResult.success(userKeyService.getUserKeyPage(queryParam));
        } catch (Exception e) {
            log.error("分页查询用户API密钥列表异常", e);
            return ResponsePageResult.fail(500, "查询失败：" + e.getMessage());
        }
    }
}
